<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item>监控管理</el-breadcrumb-item>
            <el-breadcrumb-item>集群监控</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 集群操作区 -->
        <div>
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="openDashboardAddDialog" plain>新增监控仪表盘</el-button>
            <el-button type="primary" icon="el-icon-setting" size="mini" @click="openDashboardConfigDialog" plain>初始仪表盘配置</el-button>

            <el-dropdown style="float: right; margin-left: 10px;" size="mini" split-button type="success" @click="openCustomizeChartTab('default')" @command="openCustomizeChartTab">
                自定义监控
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item icon="el-icon-pie-chart" command="Customize1">Customize1</el-dropdown-item>
                    <el-dropdown-item icon="el-icon-pie-chart" command="Customize2">Customize2</el-dropdown-item>
                    <el-dropdown-item icon="el-icon-pie-chart" command="Customize3">Customize3</el-dropdown-item>
                    <el-dropdown-item icon="el-icon-pie-chart" command="Customize4">Customize4</el-dropdown-item>
                    <el-dropdown-item icon="el-icon-pie-chart" command="Customize5">Customize5</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>

            <el-dropdown style="float: right; margin-left: 10px;" size="mini" split-button type="success" @click="openClusterChartTab('default')" @command="openClusterChartTab">
                集群监控
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item icon="el-icon-pie-chart" v-for="item in getDashboardList" :key="item.id" :command="item.id">
                        {{ item.name }}
                    </el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
        </div>
        
        <!-- 仪表盘展现区 -->
        <div class="dashboard-area" :style="`position: relative; height: ${getInnerSize.height - 193}px;`">

            <!-- 仪表盘空白占位 -->
            <div class="dashboard-cover" :style="`display: ${allTabItems.length > 0 ? 'none' : 'block'};`">
                <div style="height: 20%;"></div>
                <h1>
                    当前没有正在展现的监控仪表盘页面
                </h1>
            </div>

            <!-- 仪表盘内容信息 -->
            <el-tabs v-model="activeTabName" 
                @tab-remove="removeTab" 
                :style="`height:100%; margin-top: 5px; position: relative;`" 
                closable>

                <el-tab-pane v-for="(item) in allTabItems"
                    :key="item.name"
                    :label="item.title"
                    :name="item.name">

                    <iframe 
                        :src="item.content" 
                        :style="`height: ${getInnerSize.height - 247}px; min-height: 430px;`"
                        class="iframe" 
                        frameborder="0" 
                        scrolling="yes">
                    </iframe>
                </el-tab-pane>
            </el-tabs>
        </div>

        <!-- 新增监控仪表盘对话框 -->
        <el-dialog
            title="新增监控仪表盘"
            :visible.sync="addDashboardDialogVisible"
            width="60%">

            <!-- 提示信息 -->
            <el-alert style="margin-bottom: 5px; border: 1px dotted orange;"
                title="在以下集群列表中选择一项，点击对应的“创建仪表盘”按钮，开始为该集群配置监控页面；已创建过仪表盘的集群不能再次创建。" 
                type="warning" 
                show-icon center>
            </el-alert>

            <el-table 
                :data="clusterList" 
                style="width: 100%; padding: 0; margin: 0;" 
                height="400">
                
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-form label-position="left" inline class="table-expand">
                            <el-form-item label="系统普通用户名">
                                <span>{{ scope.row.user_normal }}</span>
                            </el-form-item>
                            <el-form-item label="数据库管理员">
                                <span>{{ scope.row.db_user }}</span>
                            </el-form-item>
                            <el-form-item label="部署路径">
                                <span>{{ scope.row.installation_path }}</span>
                            </el-form-item>
                            <el-form-item label="网关地址">
                                <el-tag style="margin-right: 5px;" type="primary" size="mini" v-for="server in scope.row.trust_servers" :key="server">
                                    {{server}}
                                </el-tag>
                            </el-form-item>
                            <el-form-item label="节点列表">
                                <span>
                                    <el-tag v-if="scope.row.nodes.length <= 0" type="warning" size="mini" >空</el-tag>
                                    <el-tag v-else style="margin-right: 5px;" type="primary" size="mini" 
                                        v-for="node in scope.row.nodes" :key="node.id" :effect="node.master ? 'dark' : ''">
                                        {{node.ipaddr}}
                                    </el-tag>
                                </span>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                
                <el-table-column prop="name" label="集群名称"></el-table-column>
                <el-table-column prop="db_port" label="端口" width="100"></el-table-column>
                <el-table-column prop="db_mode" label="兼容模式" width="150">
                    <template slot-scope="scope">
                        <el-tag size="medium" v-if="scope.row.db_mode == 'oracle'"><i class="el-icon-tickets"></i> ORACLE</el-tag>
                        <el-tag size="medium" v-else-if="scope.row.db_mode == 'pg'" type="success"><i class="el-icon-document-remove"></i> POSTGRES</el-tag>
                        <el-tag size="medium" v-else type="danger"><i class="el-icon-document-delete"></i> UNKNOW</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="virtual_ip" label="虚拟地址" width="200"></el-table-column>
                <el-table-column label="操作" width="115">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.nodes.length <= 0" type="warning" size="mini">无监控节点</el-tag>
                        <el-button v-else type="success" size="mini" @click="openDashboardCreatingPage(scope.row.id)" :disabled="scope.row.dashboard_url !== undefined">创建仪表盘</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <span slot="footer" class="dialog-footer">
                <el-button @click="addDashboardDialogVisible = false">取 消</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import { mapGetters } from 'vuex';
export default {
    data: function () {
        return {
            clusterList: [],
            maxTabsLimit: 5,
            activeTabName: '',
            allTabItems: [
                // {
                //     title: 'Baidu',
                //     name: 'Baidu',
                //     content: 'http://www.baidu.com/'
                // }, {
                //     title: 'Gitee',
                //     name: 'Gitee',
                //     content: 'https://gitee.com/'
                // }, {
                //     title: 'Grafana',
                //     name: 'Grafana',
                //     content: 'http://192.168.100.181:3000/'
                //     // content: 'http://192.168.100.181:3000/d/897596e812a848f8be6819f9113f30d9/monitor_897596e812a848f8be6819f9113f30d9?orgId=1&refresh=5s&kiosk'
                // }
            ],
            addDashboardDialogVisible: false
        }
    },
    mounted: function () {
        this.getClusterList();
    },
    computed: {
        ...mapGetters(['getInnerSize']),
        innerStyle: function () {
            return `height: ${this.getInnerSize.height - 160}px;`;
        },
        getDashboardList: function () {
            const dashboardList = [];
            this.clusterList.forEach(cluster => {
                if (cluster.dashboard_url) {
                    dashboardList.push(cluster);
                }
            });
            return dashboardList;
        }
    },
    methods: {
        getClusterList: async function () {
            const result = await this.$http.get('clusters', {
                params: {
                    query: '',
                    pagenum: 1,
                    pagesize: 9999
                }
            });
            const res = result.data;
            if (res.meta.status !== 200) return this.$message.error(`获取集群列表失败：${res.meta.msg}`);
            this.clusterList = res.data.clusters;
        },
        openClusterChartTab: function (command) {
            if (this.allTabItems.length >= this.maxTabsLimit) return this.$message.warning(`仪表盘页面开启数量已达到上限，通一时间只能打开最多 ${this.maxTabsLimit} 个页面.`);
            // console.log("Cluster Command: ", command);

            const dashboardList = this.getDashboardList;
            if (command === 'default') {
                if (dashboardList.length <= 0) return this.$message.warning(`目前还没有创建任何仪表盘页面，请先为集群创建监控仪表盘后，再由此打开仪表盘页面.`);
                command = dashboardList[0].id;
            }

            const isOpened = this.allTabItems.some(item => item.name === command.toString());
            if (!isOpened) {
                const dashboard = dashboardList.find(dashboard => dashboard.id === command);
                this.allTabItems.push(
                    {
                        title: dashboard.name,
                        name: dashboard.id.toString(),
                        content: dashboard.dashboard_url
                    }
                );
            }
            this.activeTabName = command.toString();
        },
        openCustomizeChartTab: function (command) {
            if (this.allTabItems.length >= this.maxTabsLimit) return this.$message.warning(`仪表盘页面开启数量已达到上限，通一时间只能打开最多 ${this.maxTabsLimit} 个页面.`);
            console.log("Customize Command: ", command);
        },
        openDashboardAddDialog: async function () {
            await this.getClusterList();
            if (this.clusterList.length <= 0) return;
            this.addDashboardDialogVisible = true;
        },
        openDashboardCreatingPage: function (cid) {
            this.$router.push({
                path: '/monitorDashboards/newDashboard',
                query: {
                    cid: cid
                }
            });
        },
        openDashboardConfigDialog: function () {
            console.log("配置仪表盘");
        },
        removeTab: function (targetName) {
            const tabs = this.allTabItems;
            let activeName = this.activeTabName;
            if (activeName === targetName) {
                tabs.forEach((tab, index) => {
                    if (tab.name === targetName) {
                        const nextTab = tabs[index + 1] || tabs[index - 1];
                        if (nextTab) {
                            activeName = nextTab.name;
                        }
                    }
                });
            }
            this.activeTabName = activeName;
            this.allTabItems = tabs.filter(tab => tab.name !== targetName);
        }
    }
}
</script>

<style lang="less" scoped>
    .dashboard-area {
        margin-top: 5px;
    }

    .dashboard-cover {
        position: absolute;
        background-color: rgba(245, 247, 250, .8);
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        z-index: 10;
        border-radius: 25px;
    }

    .dashboard-cover > h1 {
        font-size: 32px;
        color: white;
        text-align: center;
        text-shadow: 5px 5px 5px lightgray;
    }

    .iframe {
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }

    .table-expand {
        font-size: 0;
    }

    .table-expand label {
        width: 90px;
        color: #99a9bf;
    }

    .table-expand .el-form-item {
        margin: 0;
        margin-bottom: 0;
        width: 100%;
    }
</style>